//utf-8
#ifndef __RFMESH_H__
#define __RFMESH_H__

#include <stdint.h>
#include <string.h>
#include "bsp.h"
#include "list.h"



#define CONFIG_TASK_INTERVAL_MS   (10)    //任务轮询周期(毫秒)
#define CONFIG_ROUTETABLE_SIZE    (256)   //路由表数量，根据最大设备数 +2
#define CONFIG_RECORDPOOL         (16)    //帧记录过滤池数量
#define CONFIG_CONFIRM_INTERVAL   (50)    //帧确认间隔
#define CONFIG_HEARTBEAT_INTERVAL (2000)  //心跳周期(毫秒)
#define CONFIG_FRAME_RETRY_COUNT  (10)    //每个帧传递时重试次数
#define CONFIG_MESH_GATEWAY_ID    (1)     //当前网络的网关地址
#define CONFIG_ROUTE_TIMEOUT      (2)     //N： 无心跳(N-0)次判定断网(对节点而言)|无路由更新(N-0)次判定节点离线(对上一级而言)
#define CONFIG_BROADCAST_ID       (0xFF)  //广播地址
#define CONFIG_LOW_ENERGY         (0)


/*
CONFIG_LOW_ENERGY: 
TODO:
设备不自动联网 而是在按下发送键(wakeup)后使用广播发送一次数据随即再次进入低功耗
重启后就配置正常工作状态去睡眠(不收发数据)或者休眠 
*/


#include "cc2500.h"
#include "st7789.h"
#include <stdio.h>


#define tr printf

#define ENTER_SAFE_AREA os_enter_critical
#define EXIT_SAFE_AREA  os_exit_critical

#define OS_MALLOC os_malloc
#define OS_FREE os_free

#define OS_SLEEP os_sleep

//frame_t->type
typedef enum{
	MT_DATA,
	MT_PING,
	MT_ERROR,
	MT_HEARTBEAT,
	MT_ACK,
	MT_ROUTE,
	MT_CONFIRM,
}MSG_TYPE;




//PHY 传输帧打包格式 最大数据 24 字节
struct frame_t{
    unsigned char receiver;
    unsigned char relay;
    unsigned char dst;
    unsigned char src;
    unsigned char msgid;
    unsigned char type:4;   
    unsigned char flag:4;
   
    unsigned char payload[PHY_DATA_WIDTH -8];
    unsigned char crc_h;
    unsigned char crc_l;
};

//PHY 收发池 格式 挂载到LIST
struct xfer_pool_t{
	uint16_t serial;
	int16_t retry;
	struct frame_t frame;
	int32_t timeval;
	int32_t timeout;
	int8_t rssi;
	uint8_t  id;
	struct list_head list;
};



//RFMESH 全局变量
struct rfmesh_t{
	unsigned char prev;//上一级网关
	unsigned char msgid;//帧ID
	unsigned char level;//网络等级
	unsigned char mesh;//是否组网
	unsigned char dhcp;//如果DHCP，则自动获取网关，否则手动指定网关
	unsigned char id;
	unsigned char kalive ;//心跳计时，默认10
	unsigned int crcerr;
	unsigned int tx;
	unsigned int rx;
	unsigned int routetable_tv;
	unsigned int heartbeat_tv;
	volatile unsigned short hop_record[CONFIG_RECORDPOOL];
	volatile unsigned char route_table[CONFIG_ROUTETABLE_SIZE];
	volatile unsigned char rtv[CONFIG_ROUTETABLE_SIZE];//route table value
	volatile  int8_t rssi[CONFIG_ROUTETABLE_SIZE];
	struct list_head txlist;
	struct list_head rxlist;
};


//10ms 调用一次 影响时间： 心跳、断网检测、路由超时、数据超时
void rfmesh_task(void);

void rfmesh_init(uint8_t id);

//用于数据收发
void rfwrite(uint8_t id, void *pdata);

//接收队列随后处理时调用
void rfmesh_input(struct frame_t *pframe);

//接收到消息后存储到这里 队列形式缓存
int copyto_rxlist(int8_t rssi, struct frame_t *pframe);




#endif
